﻿using Foundation.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace Dyao.Book.Repository.Shared
{
    [ConnectionStringName("DataConn")]
    public class DataDbContext : BizDbContext<DataDbContext>
    {
        private ILoggerFactory _loggerFactory { get; set; }
        private IEnumerable<IModelCreatingHandler> _modelCreatingHandlers { get; set; }

        public DataDbContext(DbContextOptions<DataDbContext> options, ILoggerFactory loggerFactory, IServiceProvider serviceProvider, IEnumerable<IModelCreatingHandler> modelCreatingHandlers)
            : base(options, serviceProvider)
        {
            _loggerFactory = loggerFactory;
            _modelCreatingHandlers = modelCreatingHandlers;
#if DEBUG
            var id = ContextId;
            _loggerFactory.CreateLogger<DataDbContext>().LogInformation($"创建applicationDbContext，Id：{id.InstanceId}");
#endif
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseLoggerFactory(_loggerFactory);
#if DEBUG
            optionsBuilder.EnableSensitiveDataLogging();
#endif
            base.OnConfiguring(optionsBuilder);
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            var modelCreatingHandlers = _modelCreatingHandlers.Where(a => a.CreatingType == ModelCreatingType.Data || a.CreatingType == ModelCreatingType.DataView);

            foreach (var modelCreatingHandler in modelCreatingHandlers)
            {
                modelCreatingHandler.Handle(modelBuilder);
            }

            modelBuilder.AddRestrictDeleteBehaviorConvention();

            modelBuilder.DisableUnicodeIdColumn();
        }
    }
}
